<?php
require_lib('util/req_util',false);
/**
 *  ZIP邮政编码查询
 *  <br>示例:<br>
 *  require_lib('net/ZIPRegion.class',false);
 *  $zip_region=new ZIPRegion(ROOT_PATH .DS.'res/ip/qqwry.dat');
 *  print_r($zip_region->get_zipcode());
 */
class ZIPRegion
{
	private $link;

    public function __construct($file) {
    	if(! file_exists($file)) throw new Exception('ZIPRegion:zipcode.mdb file not exists,NOT FOUND '.$file);
		$constr="DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath($file);
		$this->link = odbc_connect($constr,'','',SQL_CUR_USE_ODBC);
    }

    public function __destruct() {
        odbc_close($this->link);
    }

    /**
     * 根据所给地区信息返回邮政编码
     * @param string $province  省
	 * @param string $city  市
	 * @param string $district  县区
	 * @param string $address  乡镇街道
     * @return string 邮政编码
     */
    public function get_zipcode($province='',$city='',$district='',$address='') {
        if (!$this->link) return null;

		$charset = $GLOBALS['context']->get_app_conf('charset');
		$province = mb_substr($province,0,2,$charset);
		$city = mb_substr($city,0,2,$charset);
		$district = mb_substr($district,0,2,$charset);
		$address = mb_substr($address,0,2,$charset);

		$province = iconv($charset,'GBK',$province);
		$city = iconv($charset,'GBK',$city);
		$district = iconv($charset,'GBK',$district);
		$address = iconv($charset,'GBK',$address);

		$sql = "SELECT TOP 1 ZIP
				FROM ZIPCODE
				WHERE (PROVINCE LIKE '$province%' AND CITY LIKE '$city%' AND ADDRESS LIKE '$district%') OR
					  (PROVINCE LIKE '$province%' AND ADDRESS LIKE '$district%')";
		if($address != '') $sql .= " OR (PROVINCE LIKE '$province%' AND CITY LIKE '$city%' AND ADDRESS LIKE '$address%')";

		$result = odbc_exec($this->link,$sql);
		if(!$result){
			$sql = "SELECT TOP 1 ZIP
					FROM ZIPCODE
					WHERE (PROVINCE LIKE '$province%' AND CITY LIKE '$city%')";
			$result = odbc_exec($this->link,$sql);
		}

		return odbc_result($result,'ZIP');
    }

}
